package com.example.ncov_management_system.service;

import cn.hutool.core.convert.Convert;
import com.example.ncov_management_system.dao.LoginDao;
import com.example.ncov_management_system.dao.TeacherDao;
import com.example.ncov_management_system.entity.Clbum;
import com.example.ncov_management_system.entity.Login;
import com.example.ncov_management_system.entity.Student;
import com.example.ncov_management_system.entity.Teacher;
import com.example.ncov_management_system.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
@Slf4j
public class LoginService {
    @Autowired
    private LoginDao loginDao;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;


    @Transactional
    public Login login(Login login, HttpSession session) {
        Login login_db  = loginDao.findByUsername(login.getUsername());
        if (login_db==null) {
            throw new RRException("用户名不存在");
        } else {
            if (!login_db.getPassword().equals(login.getPassword())) {
                throw new RRException("密码错误");
            }
        }
        session.setAttribute("role",login_db.getRole());
        switch (login_db.getRole()) {
            case "管理员":
                session.setAttribute("name","admin");
                break;
            case "教师":
                Teacher teacher = teacherService.findById(Convert.toLong(login.getUsername()));
                System.out.println(teacher.getClbums());
                List<Clbum> clbums = teacher.getClbums();
                log.info("{}",clbums); // 激活懒加载
                session.setAttribute("name",teacher.getName());
                session.setAttribute("clbums",clbums);
                session.setAttribute("teacher",teacher);
                break;
            case "学生":
                Student student = studentService.findById(Convert.toLong(login.getUsername()));
                session.setAttribute("name",student.getName());
                session.setAttribute("student",student);
                break;
        }
        return login_db;
    }

    public Login add(Login login) {
        return loginDao.save(login);
    }

    @Transactional
    public void editPassword(String password, long id) {
        Login login = loginDao.findById(id).get();
        login.setPassword(password);
    }

    public void deleteByUsername(String username) {
        Login login = loginDao.findByUsername(username);
        loginDao.delete(login);
    }
}
